//
//  UIImage+TYDrawImage.m
//  TYDemo
//
//  Created by Thank_hyu on 2020/10/28.
//

#import "UIImage+TYDrawImage.h"

@implementation UIImage (TYDrawImage)
+ (UIImage *)imageWithBackgroundColor:(UIColor * _Nullable)backgroundColor
                                 size:(CGSize)size
                       attributesText:(NSAttributedString * _Nullable)attributesText
                          borderColor:(UIColor * _Nullable)borderColor
                         cornerRadius:(CGFloat)cornerRadius {
    return [self imageWithBackgroundColor:backgroundColor size:size attributesText:attributesText borderColor:borderColor cornerRadius:cornerRadius borderWidth:1.0];
}

+ (UIImage *)imageWithBackgroundColor:(UIColor * _Nullable)backgroundColor
                                 size:(CGSize)size
                       attributesText:(NSAttributedString * _Nullable)attributesText
                          borderColor:(UIColor * _Nullable)borderColor
                         cornerRadius:(CGFloat)cornerRadius
                          borderWidth:(float)borderWidth {
    if (!backgroundColor) backgroundColor = [UIColor clearColor];
    if (size.width <= 0 || size.height <= 0) return nil;
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 2);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClearRect(context, rect);
    //圆角为0时，，添加2的圆角，消除锯齿
    if (cornerRadius == 0) {
        cornerRadius = 0;
    }
    
    UIBezierPath * maskPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, size.width, size.height) byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(cornerRadius, cornerRadius)];
    maskPath.lineWidth = borderWidth;
    [backgroundColor set];
    [maskPath fill];
    [maskPath closePath];
    
    //    // color
    //    CGContextSetFillColorWithColor(context, backgroundColor.CGColor);
    //    CGContextFillRect(context, rect);
    
    //添加边框
    if (borderColor) {
        UIBezierPath * maskPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(borderWidth, borderWidth, size.width - 2 * borderWidth, size.height - 2 * borderWidth) byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(cornerRadius, cornerRadius)];
        maskPath.lineWidth = borderWidth;
        [borderColor setStroke];
        [borderColor set];
        [borderColor setStroke];
        [maskPath stroke];
        [maskPath addClip];
        CGContextAddPath(context, maskPath.CGPath);
        //        CGContextClip(context);
        [maskPath closePath];
    }else{
        //设置圆角
        UIBezierPath * maskPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, size.width, size.height) byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(cornerRadius, cornerRadius)];
        CGContextAddPath(context, maskPath.CGPath);
        CGContextClip(context);
        [maskPath closePath];
    }
    
    // text
    CGSize textSize = [attributesText size];
    [attributesText drawInRect:CGRectMake((size.width - textSize.width) / 2, (size.height - textSize.height) / 2, textSize.width, textSize.height)];
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}



- (UIImage *)newImageWithSize:(CGSize)asize {
    
    UIImage *newimage;
    CGSize oldsize = self.size;
    
    CGRect rect;
    if (asize.width/asize.height > oldsize.width/oldsize.height) {
        rect.size.width = asize.height*oldsize.width/oldsize.height;
        rect.size.height = asize.height;
        rect.origin.x = (asize.width - rect.size.width)/2;
        rect.origin.y = 0;
        
    }else {
        rect.size.width = asize.width;
        rect.size.height = asize.width*oldsize.height/oldsize.width;
        rect.origin.x = 0;
        rect.origin.y = (asize.height - rect.size.height)/2;
    }
    
    UIGraphicsBeginImageContext(asize);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
    
    UIRectFill(CGRectMake(0, 0, asize.width, asize.height));//clear background
    [self drawInRect:rect];
    newimage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    return newimage;
    
}

+ (UIImage *)animatedGIFWithData:(NSData *)data {
    if (!data) {
        return nil;
    }

    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);

    size_t count = CGImageSourceGetCount(source);

    UIImage *animatedImage;

    if (count <= 1) {
        animatedImage = [[UIImage alloc] initWithData:data];
    } else {
        NSMutableArray *images = [NSMutableArray array];

        NSTimeInterval duration = 0.0f;

        for (size_t i = 0; i < count; i++) {
            CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL);

            duration += [self frameDurationAtIndex:i source:source];

            [images addObject:[UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]];

            CGImageRelease(image);
        }

        if (!duration) {
            duration = (1.0f / 10.0f) * count;
        }

        animatedImage = [UIImage animatedImageWithImages:images duration:duration];
    }

    CFRelease(source);

    return animatedImage;
}

+ (float)frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source {
    float frameDuration = 0.1f;
    CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil);
    NSDictionary *frameProperties = (__bridge NSDictionary *)cfFrameProperties;
    NSDictionary *gifProperties = frameProperties[(NSString *)kCGImagePropertyGIFDictionary];

    NSNumber *delayTimeUnclampedProp = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime];
    if (delayTimeUnclampedProp) {
        frameDuration = [delayTimeUnclampedProp floatValue];
    }
    else {

        NSNumber *delayTimeProp = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime];
        if (delayTimeProp) {
            frameDuration = [delayTimeProp floatValue];
        }
    }

    // Many annoying ads specify a 0 duration to make an image flash as quickly as possible.
    // We follow Firefox's behavior and use a duration of 100 ms for any frames that specify
    // a duration of <= 10 ms. See <rdar://problem/7689300> and <http://webkit.org/b/36082>
    // for more information.

    if (frameDuration < 0.011f) {
        frameDuration = 0.100f;
    }

    CFRelease(cfFrameProperties);
    return frameDuration;
}


- (UIImage *)circleImageWithCornerRadiusScale:(CGFloat)cornerRadiusScale {
    
    // 开始图形上下文
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
    
    // 获得图形上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    // 设置一个范围
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
     
    
    UIBezierPath * maskPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, self.size.width, self.size.height) byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(self.size.width * cornerRadiusScale, self.size.height * cornerRadiusScale)];
    CGContextAddPath(ctx, maskPath.CGPath);
    CGContextClip(ctx);
     
    // 裁剪
    CGContextClip(ctx);
    [maskPath closePath];
    
    // 将原照片画到图形上下文
    [self drawInRect:rect];
    
    // 从上下文上获取剪裁后的照片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // 关闭上下文
    UIGraphicsEndImageContext();
    
    return newImage;
}


+ (UIImage *)imageWithImage:(UIImage *)image
             attributesText:(NSAttributedString *)attributesText
           attributesCenter:(CGPoint)point {
    
    // 开始图形上下文
    UIGraphicsBeginImageContextWithOptions(image.size, NO, 0.0);
    // 设置一个范围
    CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
    
    // 将原照片画到图形上下文
    [image drawInRect:rect];
    CGSize textSize = [attributesText size];
    [attributesText drawInRect:CGRectMake(point.x - textSize.width/ 2, point.y - textSize.height/ 2, textSize.width, textSize.height)];
    // 从上下文上获取剪裁后的照片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    // 关闭上下文
    UIGraphicsEndImageContext();
    return newImage;
}

+ (UIImage *)captureScreenForView:(UIView *)currentView {
    // 开启一个绘图的上下文
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(currentView.frame.size.width, currentView.frame.size.height), NO, 0.0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor);
    CGContextFillRect(context, CGRectMake(0, 0, currentView.frame.size.width, currentView.frame.size.height));
    // 作用于CALayer层的方法。将view的layer渲染到当前的绘制的上下文中。
    [currentView drawViewHierarchyInRect:CGRectMake(0, 0, currentView.frame.size.width, currentView.frame.size.height) afterScreenUpdates:YES];
    // 获取图片
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    // 结束绘图上下文
    UIGraphicsEndImageContext();
    
    return  viewImage;
}

- (void)saveImageToPhotosAlbum {
    UIImageWriteToSavedPhotosAlbum(self, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
#pragma mark -- <保存到相册>
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    NSString *msg = nil ;
    if(error){
        msg = @"保存图片失败" ;
    }else{
        msg = @"保存图片成功" ;
    }
}
@end
